﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AtletIS.Shared.Entities;
using System.Data;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.WpfControls
{
    /// <summary>
    /// Interaction logic for ChipResults.xaml
    /// </summary>
    public partial class ChipResults : UserControl
    {
        private const int PAGE_SIZE = 8;
        private int pageIndex = 0;
        private int pages = 1;

        private DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private CheckPointsTableAdapter taCheckPoints = new CheckPointsTableAdapter();
        private ChipDataTableAdapter taChipData = new ChipDataTableAdapter();

        private System.Windows.Forms.Timer tmrRefresh;
        private DataTable dtChipData;
        private DisciplineListEntity discipline;
        private int checkPointId;
        
        // Constructor
        public ChipResults(DisciplineListEntity discipline)
        {
            InitializeComponent();
            this.discipline = discipline;

            cbTitle.title1 = discipline.Name;
            cbTitle.title2 = "Chip Results";
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // Check-pointy
            DataTable dtCheckPoints = DatabaseHelper.GetCheckPointsByDisciplineListIdActive(discipline.ID, false); 
            // taCheckPoints.GetActiveByDisciplineListId(discipline.ID);
            this.dgCheckPoints.ItemsSource = dtCheckPoints.AsDataView();
            try
            {
                if (dgCheckPoints.Items[0] != null)
                {
                    DataRowView drv = (DataRowView)dgCheckPoints.Items[0];
                    this.checkPointId = Convert.ToInt32(drv["ID"]);
                }
            }
            catch
            {

            }

            // Timer
            this.tmrRefresh = new System.Windows.Forms.Timer();
            this.tmrRefresh.Interval = 1000;
            this.tmrRefresh.Tick += new System.EventHandler(this.tmrRefresh_Tick);
            this.tmrRefresh.Enabled = true;
            this.RefreshData();
        }

        // Timer Tick
        private void tmrRefresh_Tick(object sender, EventArgs e)
        {
            this.RefreshData();
        }

        private void RefreshData()
        {
            this.lbResults.Items.Clear();

            if (dgCheckPoints.Items.Count == 0)
                return;

            this.discipline = Helpers.DisciplineListHelper.ConvertToEntity(DatabaseHelper.GetDisciplineListById(discipline.ID).Rows[0]);

            try
            {
                dtChipData = DatabaseHelper.GetChipDataByCheckPointId(this.checkPointId);

                // Pages
                if (this.dtChipData.Rows.Count % PAGE_SIZE == 0)
                    this.pages = this.dtChipData.Rows.Count / PAGE_SIZE;
                else
                    this.pages = this.dtChipData.Rows.Count / PAGE_SIZE + 1;

                // Print
                for (int i = this.pageIndex * PAGE_SIZE; i < this.pageIndex * PAGE_SIZE + PAGE_SIZE; i++)
                {
                    if (i < this.dtChipData.Rows.Count)
                    {
                        // Get and round time
                        DateTime chipDateTime = Convert.ToDateTime(this.dtChipData.Rows[i]["ChipDateTime"]);
                        chipDateTime = RoundingHelper.RoundUpDateTime(chipDateTime, discipline.ResultCode);
                        
                        string sResult = PrintHelper.PrintResult2(chipDateTime, discipline.ResultCode);

                        ChipResultBox grb = new ChipResultBox(i + 1,
                            Convert.ToInt32(this.dtChipData.Rows[i]["StartNumber"]),
                            this.dtChipData.Rows[i]["CountryId"].ToString(),
                            this.dtChipData.Rows[i]["Surname"].ToString().ToUpper() + " " + this.dtChipData.Rows[i]["FirstName"].ToString(),
                            sResult);

                        this.lbResults.Items.Add(grb);
                    }
                }

                this.footer.txtPage.Text = (this.pageIndex + 1).ToString() + " / " + this.pages.ToString();
            }
            catch (Exception ex)
            {
                tmrRefresh.Enabled = false;
                MessageBox.Show("Nastala chyba pri generovaní výsledkov!" + Environment.NewLine + ex.Message, "Chip Results", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void dgCheckPoints_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (dgCheckPoints.CurrentItem != null)
                {
                    DataRowView drv = (DataRowView)dgCheckPoints.CurrentItem;
                    this.checkPointId = Convert.ToInt32(drv["ID"]);
                }
            }
            catch { }
        }

        private void btnPrev_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.pageIndex -= 1;

                if (this.pageIndex < 0)
                    this.pageIndex = 0;

                this.RefreshData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Výsledky", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.pageIndex += 1;

                if (this.pageIndex >= this.pages)
                    this.pageIndex = this.pages - 1;

                this.RefreshData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Výsledky", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
